//Bill implement the changes for sponsor code [start]
var tmplate = {
    "myLaiSeeLocationOption": '<option value="@{channelCodeValue}">@{channelCodeName}</option>'
};
//Bill implement the changes for sponsor code [end]

function myLaiSee() {
    this.callSuper();
    this.configuration = {
        'i18n': 'nls/myLaiSee',
        'apis': '../../config/apis/myLaiSee'
    };
    this._viewIndex = 'myLaiSeeLoading';
    this.laiseeListStaff = [];
    this.totalPrizeSent = null;
    this.prizeSummary = null;
    this.lockedBonusList = null;
    this.userInfo = {};
    this.newPrizeInfo = {};
    this.isFirst = null;
    this._currentSlideIndex = 0;
    this.isMyLaiSeeWon = null;
    this.isSwiping = false;
    //this.channelCode1Array = ['','16','22','28','68','88','99'];//Bill prepare for the UAT
    this.channelCode1Array = [];
    this.channelCode2Array = [];
    this.sponsorCode = ''; //Bill implement the changes for sponsor code
    this.myLaiSeeCodeJson = {
        myLaiSeeCode1: '',
        myLaiSeeCode2: ''
    }

    this.constants = {
        splitPercent: "25%",
        settingName: 'setting',
        laiseeListName: 'laiseeList',
        resultDisplayDuration: 3000, //unit is ms
        windowWidth: 0
    }

    this.htmlContentObj = {
        indicatorElem: '<div></div>',
        collectLaisee: '<div class="ui-div-slide cs-laisee" for="slide-element" style="bottom: 58px;height: auto;">' +
                            '<div class="cs-laiseeAmountInfo"><label style="color: #8bc53f;font-size: 18px;"></label></div>' +
                           /* add by Ben for flip animation */
                           '<div class="flipArea supports3d ui-laiseeIconArea">' +
                               '<div align="center" class="icon-laiseeStaff current"></div>' +
                               '<div  class="laiseeVideo">' +
                                   '<div class="laiseeWelcomeVedio" align="center"> ' +
                                       '<video class="hidden" width="140" height="100" webkit-playsinline > ' +
                                           '<source src="" type="video/mp4"/> ' +
                                       '</video>' +
                                   '</div>' +
                               '</div>' +
                               '<div class="icon-laisee-open hidden" align="center">' +
                                   '<div class="rotateMoney hidden" style="position: absolute;width: 120px;height: 120px;left: 0px;top: 20px;">' +
                                        '<div class="iconMoney" style="-webkit-animation: fade 1s linear infinite;top:10px; left:57px;"><p><span>$</span></p></div>' +
                                        '<div class="iconMoney" style="-webkit-animation: fade 1s linear infinite; top:40px; left:78px;"><p><span>$</span></p></div>' +
                                        '<div class="iconMoney" style="-webkit-animation: fade 1s linear infinite; top:27px; left:24px;"><p><span>$</span></p></div>' +
                                        '<div class="iconMoney" style="-webkit-animation: fade 1s linear infinite; top:70px; left:20px;"><p><span>$</span></p></div>' +
                                        '<div class="iconMoney" style="-webkit-animation: fade 1s linear infinite; top:39px; left:50px;"><p><span>$</span></p></div>' +
                                        '<div class="iconMoney" style="-webkit-animation: fade 1s linear infinite; top:84px; left:69px;"><p><span>$</span></p></div>' +
                                    '</div>' +
                                   '<div class="hidden" style="position: absolute;left: 16px;top: 106px;color: #ffff84;font-size: 25px;display: inline-block;"></div>' +
                                   '<div class="cs-prize-money" style="margin: 170px 24px 0px; font-size: 30px; color: #ffff84;"></div>' +
                                   '<div class="hidden" style="padding: 5px; display: inline-block; color: #ffff84;font-size: 13px;bottom: 104px;"></div>' +
                               '</div>' +
                           '</div>' +
                           /* end add by Ben for flip animation */
                           '<div class="slideContent">' +
                               '<div><label><span class="ui-darkRedSpan ui-bigSpan"></span></label></div>' +
                               '<div><label><span class="ui-greySpan size15"></span></label></div>' +
                           '</div>' +
                       '</div>'
    };
}

// ==============================================================
// page parsing section [start]
// ==============================================================
myLaiSee.prototype.myLaiSeeLoadingHasParsed = function() {
    var self = this;

    setTimeout(function() {
        self.constants.windowWidth = window.innerWidth;
        self.getUrlParam();
    }, 1000);
}
//Dave
function getUrlValueByName(paramName){
    var paramValue="";
    var urlthis=location.href;
    urlthis=urlthis.substring(urlthis.indexOf('?')+1,urlthis.length);
    var arr=urlthis.split('&');
    if(arr!=null){
        for(var i=0;i<arr.length;i++){
            var parmNameValue=arr[i].split('=');
            if(parmNameValue!=null&&parmNameValue.length==2){
                if(parmNameValue[0]==paramName){
                    paramValue=parmNameValue[1];
                    break;
                }
            }
        }
    }
    return paramValue;
}
myLaiSee.prototype.myLaiSeeNowStaffHasParsed = function() {
    var self = this;
    var currentPage = 0;

    self.myLaiSeeNowStaffInit();

    iData.get('myLaiSeeNowStaff_btn_menu').click(function() {
        var toPage = 'file:///web/postlogon/menu/menu.html';
        if(getUrlValueByName("state")=='1'){
            toPage = 'file:///web/postlogon/menu/menu.html?state='+getUrlValueByName("state");
        }
        self.cancelShaking(self.cancelLongPress, [self.goTo, [toPage, true]]);
    });
    iData.get('btnReceived').click(function() {
        var toPage = "file:///web/postlogon/myLaisee/myLaiSee.html";
        if(getUrlValueByName("state")=='1'){
            toPage = 'file:///web/postlogon/myLaisee/myLaiSee.html?state='+getUrlValueByName("state");
        }
        self.cancelShaking(self.cancelLongPress, [self.goTo, [toPage, true]]);
    });
    iData.get('btnDelivered').click(function() {
        var toPage = "file:///web/postlogon/dashboard/dashboard.html";
        if(getUrlValueByName("state")=='1'){
            toPage = "file:///web/postlogon/dashboard/dashboard.html?state="+getUrlValueByName("state");
        }
        self.cancelShaking(self.cancelLongPress, [self.goTo, [toPage, true]]);
    });

    // Nick added help button start
    iData.get("myLaiSeeNowStaff_btn_help").click(function() {
        self.goTo("help");
    });
    // Nick added help button end

    $('#redeemList').on("click", "li", function() {
        self.redeemOptionId = $(this).attr("redeemId");
    });

    $('#redeemCancel').on("click", function() {
        $("#redeemList").addClass("hidden");
        $("#redeemPopUp").addClass("hidden");
    });

    $('#redeemContinue').on("click", function() {
        //Dave
        self.currentMoneyStr = $("#laisee-open" + (self._currentSlideIndex)).removeClass('hidden').find('div.cs-prize-money').text();
        var redeemOptionId = self.redeemOptionId;
        $("#redeemList").addClass("hidden");
        if (self.redeemOptionId == 'Donation' && self.location == iData.get('i18n').hbcn) {
            self.request({
                name: "redeemPrize",
                data: self.redeemPrizeParam,
                callback: self.redeemPrizeCallBack,
                method: "post"
            });
            return;
        }
        $("#redeemForm").removeClass("hidden");
        if (redeemOptionId == 'Money' && self.location == iData.get('i18n').htsa) {
            $('#redeemToAccount').val("");
            $('#accountName').val("");
            $("#redeemConfirm").addClass("disabled");
        } else {
            $("#redeemConfirm").removeClass("disabled");
        }
        if (redeemOptionId == 'Donation') {
            $("#donateForm").removeClass("hidden");

//            $("#donateMoney").html(self.currentMoneyStr);
            $("#donateMoney").html($("#laisee-open" + (self._currentSlideIndex+1)).removeClass('hidden').find('div.cs-prize-money').text());

//            $("#donateMoney").html(self.currentMoneyStr);
//            $("#donateMoney").html('HKD 50');

            $("#couponForm").addClass("hidden");
            $("#accountForm").addClass("hidden");
            var donationList = self.donationList;
            var donationStr = "";
            for (i = 0; i < donationList.length; i++) {
                donationStr += '<option value="' + donationList[i].optionId + '" >' + donationList[i].optionName + '</option>';
            }
            $('#donateList').empty().append(donationStr);
        } else if (redeemOptionId == 'Coupon') {
            $("#couponForm").removeClass("hidden");
            $("#couponMoney").html(self.currentMoneyStr);
            $("#donateForm").addClass("hidden");
            $("#accountForm").addClass("hidden");
            var couponList = self.couponList;
            var couponStr = "";
            for (i = 0; i < couponList.length; i++) {
                couponStr += '<option value="' + couponList[i].optionId + '" >' + couponList[i].optionName + '</option>';
            }
            $('#couponList').empty().append(couponStr);
        } else if (redeemOptionId == 'Money') {
            $("#accountForm").removeClass("hidden");

            $("#donateForm").addClass("hidden");
            $("#couponForm").addClass("hidden");
            if (self.location == iData.get('i18n').htsa) {
                $("#accountBox").removeClass("hidden");
                $("#accountMoneyHKPanel").removeClass("hidden");
                $("#accountMoneyCNPanel").addClass("hidden");
                $("#accountMoneyHK").html(self.currentMoneyStr);
            } else {
                //Dave start
                $("#accountForm").removeClass("hidden");
                $("#accountBox").removeClass("hidden");
                //Dave
                testAccount();
                //Dave end
                $("#accountMoneyHKPanel").addClass("hidden");
                $("#accountMoneyCNPanel").removeClass("hidden");
                $("#accountMoneyCN").html(self.currentMoneyStr);
//                $("#accountMoneyCN").html('HKD20');
            }
        }
    });




//Dave  keyup
    $('#redeemToAccount .ui-accountInput').click(function(){
            $(this).focus().select();
    });
    $('#redeemToAccount .ui-accountInput').keyup(function () {
        var thisval=$(this).val();
        if(thisval!=null&&thisval!=""&&thisval!=undefined){
            $(this).next().focus().select();
        }
        testAccount();
    });

//Dave
  function testAccount(){
      var err = true;
      $.each($('#redeemToAccount input'), function (index, obj) {
          var valueobj = obj.value;
          if (index <= 9) {
              if (valueobj == "" || valueobj == null || valueobj == undefined) {
                  err = false;
                  return false;
              } else {
                  if (!(valueobj >= 0 && valueobj <= 9)) {
                      err = false;
                      return false;
                  }
              }
          } else {
              if (valueobj != "" && valueobj != null && valueobj != undefined) {
                  if (!(valueobj >= 0 && valueobj <= 9)) {
                      err = false;
                      return false;
                  }
              }
          }
      });
      if (!err) {
          $('#redeemConfirm').addClass('disabled');
          $('#redeemConfirm').css('color','rgba(122,201,67,0.5)');
          return false;
      } else {
          $('#redeemConfirm').removeClass('disabled');
          $('#redeemConfirm').css('color','#8bc53f');
      }
  }


    $('#redeemConfirm').on("click", function() {
        // Nick fixed dim button issue start
        if (!$(this).hasClass("disabled")) {
            // Nick fixed dim button issue end
            self.request({
                name: "redeemPrize",
                data: self.redeemPrizeParam,
                callback: self.redeemPrizeCallBack,
                method: "post"
            });
            // Nick fixed dim button issue start
        }
        // Nick fixed dim button issue end
    });

    $('#redeemToAccount').on('input', function() {
        self.checkAccountInput();
    });
    $('#accountName').on('input', function() {
        self.checkAccountInput();
    });

    $('#redeemBack').on("click", function() {
        $("#redeemForm").addClass("hidden");
        $("#redeemList").removeClass("hidden");
        $("#couponForm").addClass("hidden");
        $("#donateForm").addClass("hidden");
        $("#accountForm").addClass("hidden");
    });

    $('#redeemOk').on("click", function() {
        $("#redeemForm").addClass("hidden");
        $("#redeemList").addClass("hidden");
        $("#couponForm").addClass("hidden");
        $("#donateForm").addClass("hidden");
        $("#accountForm").addClass("hidden");
        $("#redeemCon").addClass("hidden");
        $("#redeemPopUp").addClass("hidden");
    });

    if (self.isFirst) {
        iData.get('laiSeesScroller').find('div.cs-laiseeAmountInfo label').text(iData.get('i18n').youHaveLaisees.replace('~~1', self.laiseeListStaff.length).replace('~~2', self.laiseeListStaff.length > 1 ? iData.get('i18n').laisees : iData.get('i18n').laisee));
        $('div.ui-indicator').append($(self.htmlContentObj.indicatorElem).addClass('active'));
    }
    for (var j = 0; j < self.laiseeListStaff.length; j++) {
        if (!$("#laisee-open" + j).hasClass('cs-redeemed')) {
            //$("#laisee-open"+j).live("click",function(){
            // to fix TouchSwipe plugin issue on iOS7, use fastClick instead of click
            $("#laisee-open" + j).fastClick(function() {
                if ($(this).hasClass('cs-redeemed')) {
                    return;
                }
                self.getRedeemOption();
            });
        }
        // Nick removed duplicate event binding start
        // $("#laisee-open" + j).swipe("destroy");
        // $("#laisee-open" + j).swipe({
        //     swipeStatus: function(event, phase, direction, distance, duration, fingerCount) {
        //         self.controlSlide(phase, direction, distance);
        //     },
        // });
        // Nick removed duplicate event binding end
    }

    for (var j = 0; j < self.laiseeListStaff.length; j++) {
        //$("#laiseeIcon"+j).live("click",function(){
        // to fix TouchSwipe plugin issue on iOS7, use fastClick instead of click
        $("#laiseeIcon" + j).fastClick(function() {
            if ($(this).hasClass('icon-laiseeLockedStaff')) {
                return;
            }
            var index = $(this).attr("index");
            $("#laiseeVideo" + index).addClass('flipleft in current');
            $("#laiseeIcon" + index).removeClass('current').addClass('flipleft out');
            $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(1) label span').text(iData.get('i18n').opening)
            $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(2) label span').text(iData.get('i18n').oneMomentPls);
            setTimeout(function() {
                $("#laiseeIcon" + index).bind('webkitAnimationEnd', self.navigationEndHandler(index));
            }, 500);

            //setTimeout(self.playVideo,800)
            var myVideo = document.getElementById('myVideo' + index);
            myVideo.addEventListener("ended", function() {
                // Nick added delay after video end
                setTimeout(function() {
                    self.viewPrize();
                }, 1000);
            }, false);
            setTimeout(function() {
                myVideo.play();
            }, 800);
        });
        // Nick removed duplicate event binding start
        // $("#laiseeIcon" + j).swipe("destroy");
        // $("#laiseeIcon" + j).swipe({
        //     swipeStatus: function(event, phase, direction, distance, duration, fingerCount) {
        //         self.controlSlide(phase, direction, distance);
        //     },
        // });
        // Nick removed duplicate event binding end
    }

    // touchSwipe plugin
    // $("#laiseeSlideWrapper").swipe({
    //     swipeStatus: function(event, phase, direction, distance, duration, fingerCount) {
    //         self.controlSlide(phase, direction, distance);
    //     },
    // });
    $(".laiSeesList").swipe({
        swipeStatus: function(event, phase, direction, distance, duration, fingerCount) {
            self.controlSlide(phase, direction, distance);
        }
    });
    //Bill implement the changes for sponsor code [start]

    self.updateChannelCodeArray();

    iData.get('myLaiSeeNow_setting_save').click(function() {

        self.myLaiSeeCodeJson.myLaiSeeCode1 = iData.get('myLaiSeeNow_code1').val();
        self.myLaiSeeCodeJson.myLaiSeeCode2 = iData.get('myLaiSeeNow_code2').val();
        if (self.myLaiSeeCodeJson.myLaiSeeCode1 == '' || self.myLaiSeeCodeJson.myLaiSeeCode2 == '') {
            var codeDisplay = '';
        } else {
            var codeDisplay = self.myLaiSeeCodeJson.myLaiSeeCode1 + "." + self.myLaiSeeCodeJson.myLaiSeeCode2;
        }

        //alert("codeDisplay:"+codeDisplay);
        //self.sponsorCode = code;
        self.sponsorCode = self.combineChannelCode(self.myLaiSeeCodeJson.myLaiSeeCode1, self.myLaiSeeCodeJson.myLaiSeeCode2);
        //alert("self.sponsorCode:"+self.sponsorCode);
        iData.get('myLaiSeeNow_code_setting').html(codeDisplay);
        self.setSetting();
        //self.prepareShaking(self.hideSetting);
    });

    iData.get('myLaiSeeNow_setting_cancel').click(function() {

        iData.get('myLaiSeeNow_code1').each(function(i) {
            if ($(this).val() === self.myLaiSeeCodeJson.myLaiSeeCode1) {
                $(this).attr('checked', 'checked');
            } else {
                $(this).removeAttr('checked');
            }
        });
        iData.get('myLaiSeeNow_code2').each(function(i) {
            if ($(this).val() === self.myLaiSeeCodeJson.myLaiSeeCode2) {
                $(this).attr('checked', 'checked');
            } else {
                $(this).removeAttr('checked');
            }
        });
        iData.get('myLaiSeeNow_code1').val(self.myLaiSeeCodeJson.myLaiSeeCode1);
        iData.get('myLaiSeeNow_code2').val(self.myLaiSeeCodeJson.myLaiSeeCode2);
        self.prepareShaking(self.hideSetting);
    });
    iData.get('myLaiSeeNow_btn_setting').click(function() {
        self.cancelShaking(self.showSetting);
    });
    //Bill implement the changes for sponsor code [end]


}

//Bill implement the changes for sponsor code [start]

myLaiSee.prototype.showSetting = function() {
    var self = this;
    iData.get('myLaiSeeNow_code1').val(self.myLaiSeeCodeJson.myLaiSeeCode1);
    iData.get('myLaiSeeNow_code2').val(self.myLaiSeeCodeJson.myLaiSeeCode2);
    $('#myLaiSeeNow_setting').removeClass('hidden');
}

myLaiSee.prototype.updateChannelCodeArray = function() {
    var self = this;
    self.channelCode1Array[0] = '';
    self.channelCode2Array[0] = '';

    // for (var i = 1; i <= 90; i++) {
    //     self.channelCode1Array[i] = i + 9;
    // }
    self.channelCode1Array = ["", 16, 22, 28, 68, 88, 99];

    for (var j = 1; j <= 10; j++) {
        self.channelCode2Array[j] = j - 1;
    }
    self.updateChannelCode(self.channelCode1Array, self.channelCode2Array);
}

myLaiSee.prototype.updateChannelCode = function(channelCode1Array, channelCode2Array) {
    var self = this;
    var LocationOptionHtml = '';
    var LocationOptionHtml1 = '';
    for (var i = 0; i < channelCode1Array.length; i++) {
        var options = {
            channelCodeValue: channelCode1Array[i],
            channelCodeName: channelCode1Array[i]
        };
        LocationOptionHtml += self.parseTmplate(tmplate.myLaiSeeLocationOption, options);
    }
    iData.get('myLaiSeeNow_code1').empty().append(LocationOptionHtml);

    for (var j = 0; j < channelCode2Array.length; j++) {
        var options = {
            channelCodeValue: channelCode2Array[j],
            channelCodeName: channelCode2Array[j]
        };
        LocationOptionHtml1 += self.parseTmplate(tmplate.myLaiSeeLocationOption, options);
    }
    iData.get('myLaiSeeNow_code2').empty().append(LocationOptionHtml1);
}

myLaiSee.prototype.parseTmplate = function(tmplHtml, options) {
    var html = tmplHtml;
    for (var key in options) {
        html = html.replace(new RegExp("@{" + key + "}", "gm"), options[key]);
    }
    return html;
}

myLaiSee.prototype.prepareShaking = function(nextFn, nextFnArgs) {
    var self = this;
    self.registerMyLaiSeeListenerStaff(nextFn, nextFnArgs);
}

myLaiSee.prototype.hideSetting = function() {
    var self = this;
    // change by daniel
    $('#myLaiSeeNow_setting').addClass('hidden');
    // change by daniel end
}

myLaiSee.prototype.setSetting = function() {
    var self = this;

    self.callback4SetSetting();
}

myLaiSee.prototype.callback4SetSetting = function() {
    var self = this;
    self.prepareShaking(self.hideSetting);
}

myLaiSee.prototype.combineChannelCode = function(code1, code2) {
    var self = this;
    var code = '';
    if (code1 == '' || code2 == '') {
        self.emptySponsorCodeVal();
        code = '';
    } else {
        code = code1 + code2;
    }
    return code;
}

myLaiSee.prototype.emptySponsorCodeVal = function() {
    var self = this;
    self.sponsorCode = '';
    self.myLaiSeeCodeJson.myLaiSeeCode1 = '';
    self.myLaiSeeCodeJson.myLaiSeeCode2 = '';
    //$('#myLaiSeeNow_code1 option:first').attr('selected','selected');
    //$('#myLaiSeeNow_code2 option:first').attr('selected','selected');
    $('#myLaiSeeNow_code1 option:nth-child(1)').attr('selected', 'selected');
    $('#myLaiSeeNow_code2 option:nth-child(1)').attr('selected', 'selected');
    iData.get('myLaiSeeNow_code_setting').html('');
}
//Bill implement the changes for sponsor code [end]

// ==============================================================
// page parsing section [end]
// ==============================================================
myLaiSee.prototype.controlSlide = function(phase, direction, distance) {
    var self = this;
    if (self.isSwiping) {
        return;
    }
    if (distance <= 20) {
        return;
    }
    if (phase != 'end') {
        return;
    }
    var elm = document.querySelector('#laiSeesScroller');
    var transformStr = elm.style['transform'] || elm.style['webkitTransform'] || 'translate(0px, 0px)';
    var offsetX = parseInt(transformStr.match(/translate\((-{0,1}\d+)px,/)[1]);

    if (direction == 'right') {
        //Dave
        if(self.laiseeListStaff==null||self.laiseeListStaff==undefined){
            return ;
        }
        if(self.laiseeListStaff.length<1){
            return ;
        }
        //Dave 3,2,1
        var len=self.laiseeListStaff.length;
        if(self._currentSlideIndex>=len-1){
            self._currentSlideIndex=len-1;
        }else if(self._currentSlideIndex<=0){
            self._currentSlideIndex=0;
            return ;
        }
        console.log('prev slide');
        console.log(self._currentSlideIndex);

        self.isSwiping = true;
        offsetX += self.constants.windowWidth;
        elm.style['transform'] = 'translate(' + offsetX + 'px, 0px)';
        elm.style['-webkit-transform'] = 'translate(' + offsetX + 'px, 0px)';
        elm.style['-moz-transform'] = 'translate(' + offsetX + 'px, 0px)';
        elm.style['-ms-transform'] = 'translate(' + offsetX + 'px, 0px)';

        self.showPrevSlide();
    } else if (direction == 'left') {
        //Dave 0,1,2
        var len=self.laiseeListStaff.length;
        if(self._currentSlideIndex>=len-1){
            self._currentSlideIndex=len-1;
            return;
        }else if(self._currentSlideIndex<=0){
            self._currentSlideIndex=0;
        }
        console.log('next slide');
        console.log(self._currentSlideIndex);

        self.isSwiping = true;
        offsetX -= self.constants.windowWidth;
        elm.style['transform'] = 'translate(' + offsetX + 'px, 0px)';
        elm.style['-webkit-transform'] = 'translate(' + offsetX + 'px, 0px)';
        elm.style['-moz-transform'] = 'translate(' + offsetX + 'px, 0px)';
        elm.style['-ms-transform'] = 'translate(' + offsetX + 'px, 0px)';

        self.showNextSlide();
    }
}

// Nick added for help button start
myLaiSee.prototype.updateHelpButtonStatus = function() {
    var self = this,
        $laiSeesScroller = iData.get("laiSeesScroller"),
        $openLaiSee = $laiSeesScroller.children("div:eq(" + self._currentSlideIndex + ")").find(".icon-laisee-open"),
        $helpBtn = iData.get("myLaiSeeNowStaff_btn_help");
    if ($openLaiSee.length > 0 && !($openLaiSee.hasClass("hidden") || $openLaiSee.hasClass("cs-redeemed"))) {
        $helpBtn.removeClass("hidden");
        $laiSeesScroller.closest(".subPage").find(".ui-header").addClass("nav-help");
    } else {
        $helpBtn.addClass("hidden");
        $laiSeesScroller.closest(".subPage").find(".ui-header").removeClass("nav-help");
    }
};
// Nick added for help button end

myLaiSee.prototype.showPageFromLoading = function(pageId) {
    var self = this;
    setTimeout('iFunction.delegate.viewIndex="' + pageId + '";iFunction.delegate.hideLoadingMask();', 500);
}

myLaiSee.prototype.getUrlParam = function() {
    var self = this;
    if (/isFirstLogon=true/.test(location.search)) { // this is the first time logon
        self.isFirst = true;
        //self.displayTutorial();
    }
    if (self.configuration.settings.isBrowser) {
        self.callback4GetUserInfo('{"account":"43211234","fullName":"John Smith","location":"GLTc"}');
    } else {
        self.getter(self.configuration.settings.GreenPacket.customerInfo.name, self.callback4GetUserInfo);
    }
}
myLaiSee.prototype.getRedeemOption = function() {
    var self = this;
    self.request({
        name: "getRedeemOptions",
        data: self.getRedeemOptionsParam,
        callback: self.getRedeemOptionCallBack,
        method: "post"
    });
}

myLaiSee.prototype.getRedeemOptionsParam = function() {
    var self = this;
    return {
        "deviceId": self.deviceId,
        "account": self.account,
        "location": self.location
    };
}

myLaiSee.prototype.checkAccountInput = function() {
    var self = this;
    var inputArray = [$('#redeemToAccount').val(), $('#accountName').val()];
    self.checkInput(inputArray, $('#redeemConfirm'));
}

myLaiSee.prototype.checkInput = function(inputArray, dimButton) {
    for (var i = 0; i < inputArray.length; i++) {
        if (inputArray[i] == "" || inputArray[i] === undefined) {
            dimButton.addClass("disabled");
            return
        }
    }
    dimButton.removeClass("disabled");
}

myLaiSee.prototype.redeemPrizeParam = function() {
    var self = this;
    var param = {
        "requestName": "viewPrize",
        "account": self.account,
        "deviceId": self.deviceId,
        "prizeId": self.laiseeListStaff[self._currentSlideIndex - 1].prizeId
    };
    if (self.redeemOptionId == 'Donation') {
        if (self.location == iData.get('i18n').hbcn) {
            param.redeemOptionId = self.donationList[0].optionId;
        } else {
            param.redeemOptionId = $('#donateList').val();
        }
    } else if (self.redeemOptionId == 'Coupon') {
        param.redeemOptionId = $('#couponList').val();
    } else if (self.redeemOptionId == 'Money') {
        param.redeemOptionId = self.accountRedeemOptionId;
        if (self.location == iData.get('i18n').htsa) {
            param.redeemToAccount = $('#redeemToAccount').val();
            param.accountName = $('#accountName').val();
        }
    }
    return param;
}

myLaiSee.prototype.redeemPrizeCallBack = function() {
    var self = this;
    return {
        "success": function(callback) {
            var data = callback.data;
            var redeemInfo = '';
            var currentLaiseeDiv = $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex);

            $("#redeemForm").addClass("hidden");
            $("#redeemList").addClass("hidden");
            $("#couponForm").addClass("hidden");
            $("#donateForm").addClass("hidden");
            $("#accountForm").addClass("hidden");
            $("#redeemCon").removeClass("hidden");
            $("#redeemPopUp").removeClass("hidden");

            currentLaiseeDiv.find('div.slideContent div:nth-child(1) label span').addClass('ui-greySpan').removeClass('ui-darkRedSpan ui-bigSpan').
            text(iData.get('i18n').redeemOn.replace('~~1', data.body.redeemDate));

            $('#laisee-open' + (self._currentSlideIndex - 1)).addClass('cs-redeemed').find('div.cs-prize-money ~ div').removeClass('hidden').text(iData.get('i18n').redeemed);
            switch (self.redeemOptionId) {
                case 'Donation':
                    redeemInfo = '<span class="ui-redSpan">' + iData.get('i18n').donate2charity + '</span>';
                    break;
                case 'Coupon':
                    redeemInfo = '<span class="ui-redSpan">' + iData.get('i18n').eCoupon + '</span>';
                    break;
                case 'Money':
                    redeemInfo = '<span class="ui-redSpan">' + iData.get('i18n').credit2account + '</span>';
                    break;
            }
            currentLaiseeDiv.find('div.slideContent div:nth-child(2) label span').html(iData.get('i18n').youHaveChosen.replace('~~1', redeemInfo));
        },
        "error": function(callback) {
            var data = callback.data;
        }
    };
}
myLaiSee.prototype.getRedeemOptionCallBack = function() {
    var self = this;
    return {
        "success": function(callback) {
            var data = callback.data;
            var redeemList = [{
                'id': 'Donation',
                'desc': iData.get('i18n').donateDesc,
                'isExist': false
            },
//                {
//                'id': 'Coupon',
//                'desc': iData.get('i18n').couponDesc,
//                'isExist': false
//            },
                {
                'id': 'Money',
                'desc': iData.get('i18n').accountDesc,
                'isExist': false
            }];

            var redeemOptionList = data.body.redeemOptionList;
            var donationList = new Array();
            var couponList = new Array();
            var isHaveDonation = false;
            var isHaveCounpon = false;
            var isHaveMoney = false;
            for (i = 0; i < redeemOptionList.length; i++) {
                var obj = redeemOptionList[i];
                if (obj.category == 'Donation') {
                    var donationObj = new Object();
                    donationObj.optionId = obj.optionId;
                    donationObj.optionName = obj.optionName;
                    donationList.push(donationObj);
                    isHaveDonation = true;
                }
                if (obj.category == 'Coupon') {
                    var couponObj = new Object();
                    couponObj.optionId = obj.optionId;
                    couponObj.optionName = obj.optionName;
                    couponList.push(couponObj);
                    isHaveCounpon = true;
                } else if (obj.category == 'Money') {
                    isHaveMoney = true;
                    self.accountRedeemOptionId = obj.optionId;
                }
            }

            if (redeemOptionList.length == 1 && isHaveMoney == true) {
                self.redeemOptionId = 'Money';
                self.request({
                    name: "redeemPrize",
                    data: self.redeemPrizeParam,
                    callback: self.redeemPrizeCallBack,
                    method: "post"
                });
                return;
            }
            self.donationList = donationList;
            self.couponList = couponList;
            $("#redeemUl").empty();
            var redeemStr = "";

            for (i = 0; i < redeemList.length; i++) {
                if ((redeemList[i].id == 'Donation' && isHaveDonation) || (redeemList[i].id == 'Coupon' && isHaveCounpon) || (redeemList[i].id == 'Money' && isHaveMoney)) {
                    redeemList[i].isExist = true;
                }
                if (redeemList[i].isExist) {
                    redeemStr += '<li redeemId="' + redeemList[i].id + '">' + redeemList[i].desc + '<input type="radio" name="redeemOption"></li>';
                }
            }

            $("#redeemUl").append(redeemStr);
            $("#redeemList").removeClass("hidden");
            $("#redeemPopUp").removeClass("hidden");

            $("#redeemUl").find("li:first").find("input").attr("checked", "checked");
            self.redeemOptionId = $("#redeemUl").find("li:first").attr("redeemId")
//            var h = $("#redeemList").parent().height();
//            var adjustH = h - 40 - 58;
//            $("#redeemList").height(adjustH);
//            $("#redeemForm").height(adjustH);
//            $("#redeemCon").height(adjustH);
        },
        "error": function(callback) {
            var data = callback.data;
        }
    };
}

myLaiSee.prototype.displayTutorial = function() {
    var self = this;
    $('#myLaiSeeNow_tutorial').removeClass('hidden');
    self.prepareShakingStaff(self.showPageFromLoading, ['myLaiSeeNowStaff']);
}

myLaiSee.prototype.closeTutorial = function() {
    var self = this;
    self.isFirst = false;
    self.isMyLaiSeeWon = true;
    $('#myLaiSeeNow_tutorial').addClass('hidden');
    self.openInfoSection(iData.get('myLaiSeeNowStaff_topSection'), iData.get('myLaiSeeNowStaff_bottomSection'), iData.get('myLaiSeeNowStaff_info'));
    iData.get('congratsMsg').find('label > span').html(iData.get('i18n').receiveFirstNewYearLaisee);
    self.showResult(iData.get('myLaiSeeNowStaff_info').find('div.ui-waiting'), iData.get('myLaiSeeNowStaff_info').find('div.ui-result'));
}

myLaiSee.prototype.openInfoSection = function(topDiv, bottomDiv, infoDiv) {
    var self = this;
    $('#myLaiSeeNowStaff div.subPage[for=split]').removeClass('hidden');
    $('#myLaiSeeNowStaff div.subPage[for=slide]').addClass('hidden');
    infoDiv.removeClass('hidden');
    bottomDiv.animate({
        bottom: "-" + self.constants.splitPercent
    }, 500).addClass('shadow');
    topDiv.animate({
        top: "-" + self.constants.splitPercent
    }, 500).addClass('shadow');
}

myLaiSee.prototype.closeInfoSection = function(topDiv, bottomDiv, infoDiv) {
    var self = this;
    bottomDiv.animate({
        bottom: "0%"
    }, 500, function() {
        this.removeClass('shadow')
    });
    topDiv.animate({
        top: "0%"
    }, 500, function() {
        this.removeClass('shadow');
        $('#myLaiSeeNowStaff div.subPage[for=slide]').removeClass('hidden');
        $('#myLaiSeeNowStaff div.subPage[for=split]').addClass('hidden');
        //infoDiv.addClass('hidden');
        self.prepareShakingStaff(self.hideResult, [infoDiv.find('div.ui-waiting'), infoDiv.find('div.ui-result')]);
    });
}

myLaiSee.prototype.showResult = function(waitingDiv, resultDiv) {
    var self = this;
    waitingDiv.fadeOut('slow', function() {
        resultDiv.hide().removeClass('hidden').fadeIn('slow');
        self.playSound(self.isMyLaiSeeWon ? 'match' : 'unmatch');
        setTimeout(function() {
            self.getMyPrizes();
        }, self.constants.resultDisplayDuration);
    });
}

myLaiSee.prototype.hideResult = function(waitingDiv, resultDiv) {
    waitingDiv.show();
    waitingDiv.removeClass('hidden');
    resultDiv.addClass('hidden');
	iData.get('myLaiSeeNowStaff_info').find('div.ui-error').addClass('hidden');
	iData.get('myLaiSeeNowStaff_info').find('div.ui-error-collected').addClass('hidden');
}

myLaiSee.prototype.myLaiSeeNowStaffInit = function() {
    var self = this;
    $('#myLaiSeeNowStaff div.subPage[for=slide]').removeClass('hidden');
    $('#myLaiSeeNowStaff div.subPage[for=split]').addClass('hidden');
}

myLaiSee.prototype.prepareLaiseeViewStaff = function() {
    var self = this;
    var divHTML = self.htmlContentObj.collectLaisee;
    var className, days, amount, pinCode, $divHTML, redeemInfo;
    $('div.cs-laisee').remove(); // to clean laisee list in DOM
    for (var i = 0; i < self.laiseeListStaff.length; i++) {
        if (self.laiseeListStaff[i].status == 'Locked') {
            className = 'icon-laiseeLockedStaff';
        } else {
            className = '';
        }
        days = Math.ceil((new Date(self.laiseeListStaff[i].expireDate) - new Date()) / (1000 * 60 * 60 * 24));
        amount = self.laiseeListStaff[i].currency + " " + self.laiseeListStaff[i].money;
        $divHTML = $(divHTML);
        if (className) {
            $divHTML.find('div.ui-laiseeIconArea > div:nth-child(1)').addClass(className);
        }

        $divHTML.find('.icon-laiseeStaff').attr('id', 'laiseeIcon' + i);
        $divHTML.find('.icon-laiseeStaff').attr('index', i);
        $divHTML.find('.laiseeVideo').attr('id', 'laiseeVideo' + i);
        $divHTML.find("video").attr('id', 'myVideo' + i);
        $divHTML.find(".icon-laisee-open").attr('id', 'laisee-open' + i);
        // Nick added for dynamic video
        var sponsor = self.laiseeListStaff[i].sponsor,
            videoList = self.configuration.settings.GreenPacket.videoList,
            videoName = "";
        if (self.location === "GSC") {
            $divHTML.find("#myVideo" + i).find("source").attr("src", videoList.GSC);
        } else {
            videoName = videoList[sponsor];
            if (videoName) {
                $divHTML.find("#myVideo" + i).find("source").attr("src", videoName);
            } else {
                $divHTML.find("#myVideo" + i).find("source").attr("src", videoList.welcome);
            }
        }
        // Nick added for dynamic video
//Locked  Active  Opened  Redeemed
        if (self.laiseeListStaff[i].status == 'Locked') {
            $divHTML.find('div.slideContent div:nth-child(1) label span').text(iData.get('i18n').bigLaisee);

            $divHTML.find('div.slideContent div:nth-child(2) label span').text(iData.get('i18n').goToUnlock);
            $divHTML.find('div.slideContent div:nth-child(2) label span').removeClass("size15");
            $divHTML.find('div.slideContent div:nth-child(2) label span').addClass("size20");
        } else if (self.laiseeListStaff[i].status == 'Active') {
            $divHTML.find('div.slideContent div:nth-child(1) label span').text(iData.get('i18n').tap2open);

            $divHTML.find('div.slideContent div:nth-child(2) label span').text(iData.get('i18n').expireDays.replace('~~1', days));
            // Nick added to hide expire days
            $divHTML.find('div.slideContent div:nth-child(2) label span').addClass("hidden");
        } else if (self.laiseeListStaff[i].status == 'Opened') {
            $divHTML.find('div.slideContent div:nth-child(1) label span').text(iData.get('i18n').tap2redeem);

            $divHTML.find("#laiseeVideo" + i).addClass('hidden');
            $divHTML.find("#laiseeIcon" + i).addClass('hidden');
            $divHTML.find("#laisee-open" + i).removeClass('hidden');

            $divHTML.find('#laisee-open' + i + ' div.cs-prize-money').html("<sup style='font-size: 10px'>" + self.laiseeListStaff[i].currency + "</sup> " + self.laiseeListStaff[i].money);
            //Dave start
            $divHTML.find('#laisee-open' + i + ' div.cs-prize-money').next().removeClass('hidden');
            $divHTML.find('#laisee-open' + i + ' div.cs-prize-money').next().text(self.laiseeListStaff[i].sponsor);

            $divHTML.find('#laisee-open' + i + ' div.rotateMoney').removeClass('hidden');

            $divHTML.find('div.cs-laiseeAmountInfo label').css('display','none');
            //Dave end
            $divHTML.find('div.slideContent div:nth-child(2) label span').text(iData.get('i18n').help4moreDetail);
        } else if (self.laiseeListStaff[i].status == 'Redeemed') {
            $divHTML.find('div.slideContent div:nth-child(1) label span').addClass('ui-greySpan').removeClass('ui-darkRedSpan ui-bigSpan').text(iData.get('i18n').redeemOn.replace('~~1', self.laiseeListStaff[i].redeemDate));

            $divHTML.find("#laiseeVideo" + i).addClass('hidden');
            $divHTML.find("#laiseeIcon" + i).addClass('hidden');
            $divHTML.find("#laisee-open" + i).addClass('cs-redeemed').removeClass('hidden');
            $divHTML.find('#laisee-open' + i + ' div.cs-prize-money').prev().removeClass('hidden');
            $divHTML.find('#laisee-open' + i + ' div.cs-prize-money').prev().text(iData.get('i18n').redeemed);
            $divHTML.find('#laisee-open' + i + ' div.cs-prize-money').html("<sup style='font-size:10px;'>"+self.laiseeListStaff[i].currency + "</sup> " + self.laiseeListStaff[i].money).find(" ~ div").removeClass('hidden').text(iData.get('i18n').redeemed);
            //Dave start
            $divHTML.find('#laisee-open' + i + ' div.cs-prize-money').next().removeClass('hidden');
            $divHTML.find('#laisee-open' + i + ' div.cs-prize-money').next().text(self.laiseeListStaff[i].sponsor);
            $divHTML.find('div.cs-laiseeAmountInfo label').css('display','none');
            redeemInfo = '';
            switch (self.laiseeListStaff[i].redeemCategory) {
                case 'Donation':
                    redeemInfo = '<span class="ui-redSpan">' + iData.get('i18n').donate2charity + '</span>';
                    break;
                case 'Coupon':
                    redeemInfo = '<span class="ui-redSpan">' + iData.get('i18n').eCoupon + '</span>';
                    break;
                case 'Money':
                    redeemInfo = '<span class="ui-redSpan">' + iData.get('i18n').credit2account + '</span>';
                    break;
            }
            $divHTML.find('div.slideContent div:nth-child(2) label span').html(iData.get('i18n').youHaveChosen.replace('~~1', redeemInfo));
        }
        $('#laiseeSlideWrapper #laiSeesScroller').append($divHTML);
    }

    // steve bossname
    //iData.get('laiSeesScroller').find('div.cs-laiseeAmountInfo label').text(iData.get('i18n').youHaveLaisees.replace('~~1', self.laiseeListStaff.length).replace('~~2', self.laiseeListStaff.length > 1 ? iData.get('i18n').laisees : iData.get('i18n').laisee));
    if(self.laiseeListStaff!=null&&self.laiseeListStaff!=undefined){
        if(self.laiseeListStaff.length>=1){
            iData.get('laiSeesScroller').find('div.cs-laiseeAmountInfo label').text(iData.get('i18n').fromSpace + self.laiseeListStaff[self._currentSlideIndex].sponsor);
        }
    }
    var divStr;
    $('div.ui-indicator div').remove();
    for (var i = 0; i < self.laiseeListStaff.length; i++) {
        if (i == 0) {
            divStr = $(self.htmlContentObj.indicatorElem).addClass('active');
        } else {
            divStr = $(self.htmlContentObj.indicatorElem);
        }
        $('div.ui-indicator').append(divStr);
    }

    // setWidth for iScroll plugin
    self.setIScrollWidth();

    if ($('#myLaiSeeNowStaff').hasClass('parse')) {
        // bind open & redeem event
        for (var j = 0; j < self.laiseeListStaff.length; j++) {
            if (!$("#laisee-open" + j).hasClass('cs-redeemed')) {
                //$("#laisee-open"+j).live("click",function(){
                // to fix TouchSwipe plugin issue on iOS7, use fastClick instead of click
                $("#laisee-open" + j).fastClick(function() {
                    if ($(this).hasClass('cs-redeemed')) {
                        return;
                    }
                    self.getRedeemOption();
                });
            }

            // Nick removed duplicate event binding start
            // $("#laisee-open" + j).swipe("destroy");
            // $("#laisee-open" + j).swipe({
            //     swipeStatus: function(event, phase, direction, distance, duration, fingerCount) {
            //         self.controlSlide(phase, direction, distance);
            //     },
            // });
            // Nick removed duplicate event binding end

            // Nick removed duplicate event binding start
            // $("#laiseeIcon" + j).swipe("destroy");
            // $("#laiseeIcon" + j).swipe({
            //     swipeStatus: function(event, phase, direction, distance, duration, fingerCount) {
            //         self.controlSlide(phase, direction, distance);
            //     },
            // });
            // Nick removed duplicate event binding end

            //$("#laiseeIcon"+j).live("click",function(){
            // to fix TouchSwipe plugin issue on iOS7, use fastClick instead of click
            $("#laiseeIcon" + j).fastClick(function() {
                if ($(this).hasClass('icon-laiseeLockedStaff')) {
                    return;
                }
                var index = $(this).attr("index");
                $("#laiseeVideo" + index).addClass('flipleft in current');
                $("#laiseeIcon" + index).removeClass('current').addClass('flipleft out');
                $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(1) label span').text(iData.get('i18n').opening)
                $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(2) label span').text(iData.get('i18n').oneMomentPls);
                setTimeout(function() {
                    $("#laiseeIcon" + index).bind('webkitAnimationEnd', self.navigationEndHandler(index));
                }, 500);

                //setTimeout(self.playVideo,800)
                var myVideo = document.getElementById('myVideo' + index);
                myVideo.addEventListener("ended", function() {
                    // Nick added delay after video end
                    setTimeout(function() {
                        self.viewPrize();
                    }, 1000);
                }, false);
                setTimeout(function() {
                    myVideo.play();
                }, 800);
            });
        }
        self.closeInfoSection(iData.get('myLaiSeeNowStaff_topSection'), iData.get('myLaiSeeNowStaff_bottomSection'), iData.get('myLaiSeeNowStaff_info'));
    } else {
        self.prepareShakingStaff(self.showPageFromLoading, ['myLaiSeeNowStaff']);
    }
}

/*add by Ben for flip animation */
myLaiSee.prototype.playVideo = function() {
    var myVideo = document.getElementById('myVideo');
    myVideo.play();
}
myLaiSee.prototype.navigationEndHandler = function(myIndex) {
    var self = this;
    var finalAnimationName = "flipleft";
    $("#laiseeIcon" + myIndex).unbind('webkitAnimationEnd', self.navigationEndHandler);
    $("#laiseeIcon" + myIndex).removeClass('current ' + finalAnimationName + ' out');
    $("#laiseeVideo" + myIndex).removeClass(finalAnimationName);
    $("#myVideo" + myIndex).removeClass("hidden");
}
/*end add by Ben for flip animation */

myLaiSee.prototype.showPrevSlide = function(newSlideIndex) {
    var self = this;
    self._currentSlideIndex = newSlideIndex || self._currentSlideIndex - 1;
    if(self.laiseeListStaff!=null&&self.laiseeListStaff!=undefined){
        if(self.laiseeListStaff.length>=1){
            iData.get('laiSeesScroller').find('div.cs-laiseeAmountInfo label').text(iData.get('i18n').fromSpace + self.laiseeListStaff[self._currentSlideIndex].sponsor);
        }
    }
    //update indicator layout
    iData.get("indicator").children("div.active").removeClass("active");
    iData.get("indicator").children("div:nth-child(" + (self._currentSlideIndex + 1) + ")").addClass("active");

    self.isSwiping = false;
}

myLaiSee.prototype.showNextSlide = function(newSlideIndex) {
    var self = this;
    self._currentSlideIndex = newSlideIndex || self._currentSlideIndex + 1;
    iData.get('laiSeesScroller').find('div.cs-laiseeAmountInfo label').text(iData.get('i18n').fromSpace + self.laiseeListStaff[self._currentSlideIndex].sponsor);
   
    //update indicator layout
    iData.get("indicator").children("div.active").removeClass("active");
    iData.get("indicator").children("div:nth-child(" + (self._currentSlideIndex + 1) + ")").addClass("active");

    self.isSwiping = false;
}

myLaiSee.prototype.displayLaisee = function() {
    var self = this;
    if (self.newPrizeInfo.category == 'Bonus') {
        iData.get('congratsMsg').find('label > span').html(iData.get('i18n').receiveLaisee.replace('~~1', '<span class="ui-redSpan">' + iData.get('i18n').bonus + '</span>').replace('~~2', self.newPrizeInfo.sponsor || ''));
    } else if (self.newPrizeInfo.category == 'Green') {
        iData.get('congratsMsg').find('label > span').html(iData.get('i18n').receiveLaisee.replace('~~1', '<span class="ui-greenSpan">' + iData.get('i18n').green + '</span>').replace('~~2', self.newPrizeInfo.sponsor || ''));
    }
    if (self.newPrizeInfo.status == 'Active') {
        $('#myLaiSeeNowStaff_info div.staffResultContent').addClass('unlocked');
    } else if (self.newPrizeInfo.status == 'Locked') {
        $('#myLaiSeeNowStaff_info div.staffResultContent').removeClass('unlocked');
    }
    self.showResult(iData.get('myLaiSeeNowStaff_info').find('div.ui-waiting'), iData.get('myLaiSeeNowStaff_info').find('div.ui-result'));
}

myLaiSee.prototype.checkLaiseeStatus = function() {
    var self = this;
    // Nick added for help button start
    self.updateHelpButtonStatus();
    // Nick added for help button end
    if (self._currentSlideIndex == 0) {
        return;
    }
    if (self.laiseeListStaff[self._currentSlideIndex - 1].status == 'Locked') {
        self.prepareLongPress();
    }
}

myLaiSee.prototype.prepareShakingStaff = function(nextFn, nextFnArgs) {
    var self = this;
    self.registerMyLaiSeeListenerStaff(nextFn, nextFnArgs);
}

myLaiSee.prototype.cancelShaking = function(nextFn, nextFnArgs) {
    var self = this;
    self.unRegisterMyLaiSeeListener(nextFn, nextFnArgs);
}

myLaiSee.prototype.prepareLongPress = function(nextFn, nextFnArgs) {
    var self = this;
    self.registerLongPressListenerStaff(nextFn, nextFnArgs);
}

myLaiSee.prototype.cancelLongPress = function(nextFn, nextFnArgs) {
    var self = this;
    self.unRegisterLongPressListener(nextFn, nextFnArgs);
}

myLaiSee.prototype.setIScrollWidth = function() {
    var self = this;
    var numOfSlide = iData.get("laiSeesScroller").children("div").length;
    iData.get("laiSeesScroller").width(self.constants.windowWidth * numOfSlide).children("div").width(self.constants.windowWidth).height('340px');
//    iData.get("laiSeesScroller").width(self.constants.windowWidth * numOfSlide).children("div").width(self.constants.windowWidth);
}
// ==============================================================
// Native hook call section [start]
// ==============================================================
myLaiSee.prototype.callback4GetUserInfo = function(data) {
    var self = this;
    try {
        self.userInfo = $.parseJSON(data);
    } catch (e) {}
    self.getCustomerInfo();
}


myLaiSee.prototype.getCustomerInfo = function(data) {
    var self = this;
    self._customerInfo = self.configuration.settings.GreenPacket.customerInfo;
    self.getter(self._customerInfo.name, self.getCustomerDataCallback);
}

myLaiSee.prototype.getCustomerDataCallback = function(customerData) {
    var self = this;

    if (self.configuration.settings.isBrowser) {
//        customerData = '{"account": "12345678", "fullName": "Nick X L AO", "location": "GLTc"}';
        customerData = '{"account": "12345678", "fullName": "Nick X L AO", "secureToken": "411768490e203d7171fcd0047754c88454485b74de6863edab12bc043ea3e58", "location": "GLTc"}';
    }
    customerData = JSON.parse(customerData || "{}");

    //Dave start
        if(customerData.secureToken==undefined||customerData.secureToken==""||customerData.secureToken==null){
            $('#btnDelivered').hide();
            $('#btnReceived').hide();
        }
    //Dave end

    // get keyNames from global config
    var customerInfo = self._customerInfo,
        properties = customerInfo.properties;
    self.account = customerData[properties.account];
    self.secureToken = customerData[properties.secureToken];
    self.location = customerData[properties.location];
    if (self.configuration.settings.isBrowser) {
        var img = new Image();
        img.src = '../../../lib/images/lock@2x.png';
        self.callback4GetEncryptedDeviceId('E812H39DK2L,9247611KDL01L23302138DDDF');
    } else {
        self.getEncryptedDeviceId(self.callback4GetEncryptedDeviceId);
    }
};

myLaiSee.prototype.callback4GetEncryptedDeviceId = function(data) {
    var self = this;
    self.deviceId = data;
    if (self.deviceId) {
        if (self.isFirst) {
            self.displayTutorial();
        } else {
            self.getMyPrizes();
        }
    } else {
        $('div.ui-error-panel>p').html(self._err['noService']);
       self.showPageFromLoading('errorWrapper');
    }
}

myLaiSee.prototype.registerMyLaiSeeListenerStaff = function(nextFn, nextFnArgs) {
    var self = this;
    if (!nextFnArgs) {
        nextFnArgs = [];
    }
    if (!nextFn) {
        nextFn = self.pseudoCallback;
    }
    if (self.configuration.settings.isBrowser) {
        self.registerMyLaiSeeListener(self.listener4RegisterMyLaiSeeListenerStaff, function() {
            nextFn.apply(this, nextFnArgs);
        });
        (function() {
            nextFn.apply(self, nextFnArgs);
        })();
    } else {
        self.registerMyLaiSeeListener(self.listener4RegisterMyLaiSeeListenerStaff, function() {
            nextFn.apply(this, nextFnArgs);
        });
    }
}
myLaiSee.prototype.listener4RegisterMyLaiSeeListenerStaff = function() {
    var self = this;
    if (self.isFirst) {
        self.cancelShaking(self.closeTutorial);
    } else {
        self.cancelShaking(self.joinMyLaiSeeGame);
    }
}

myLaiSee.prototype.unRegisterMyLaiSeeListener = function(nextFn, nextFnArgs) {
    var self = this;
    if (!nextFnArgs) {
        nextFnArgs = [];
    }
    if (self.configuration.settings.isBrowser) {
        (function() {
            nextFn.apply(self, nextFnArgs);
        })();
    } else {
        self.unregisterMyLaiSeeListener(function() {
            nextFn.apply(this, nextFnArgs);
        });
    }
}

myLaiSee.prototype.registerLongPressListenerStaff = function(nextFn, nextFnArgs) {
    var self = this;
    if (!nextFnArgs) {
        nextFnArgs = [];
    }
    if (!nextFn) {
        nextFn = self.pseudoCallback;
    }
    console.log('registerLongPressListenerStaff');
    if (self.configuration.settings.isBrowser) {
        console.log(self.getParam4RegisterLongPressListenerStaff());
        self.registerLongPressListener(self.getParam4RegisterLongPressListenerStaff(), self.listener4RegisterLongPressListenerStaff, function() {
            nextFn.apply(this, nextFnArgs);
        });
        (function() {
            nextFn.apply(self, nextFnArgs);
        })();
    } else {
        self.registerLongPressListener(self.getParam4RegisterLongPressListenerStaff(), self.listener4RegisterLongPressListenerStaff, function() {
            nextFn.apply(this, nextFnArgs);
        });
    }
}
myLaiSee.prototype.getParam4RegisterLongPressListenerStaff = function() {
    var self = this;
    //var x1 = $('#laiseeIcon'+(self._currentSlideIndex-1)).offset().left * window.devicePixelRatio;
    var x1 = (self.constants.windowWidth / 2 - 81) * window.devicePixelRatio;
    var y1 = $('#laiseeIcon' + (self._currentSlideIndex - 1)).offset().top * window.devicePixelRatio;
    //var x2 = $('#laiseeIcon'+(self._currentSlideIndex-1)).width() * window.devicePixelRatio +x1;
    var x2 = (self.constants.windowWidth / 2 + 81) * window.devicePixelRatio;
    var y2 = $('#laiseeIcon' + (self._currentSlideIndex - 1)).height() * window.devicePixelRatio + y1;
    return '{"topleft_x":' + x1 + ',"topleft_y":' + y1 + ',"bottomright_x":' + x2 + ',"bottomright_y":' + y2 + '}';
}
myLaiSee.prototype.listener4RegisterLongPressListenerStaff = function() {
    var self = this;
    self.cancelLongPress(self.unlockBonus);
}

myLaiSee.prototype.unRegisterLongPressListener = function(nextFn, nextFnArgs) {
    var self = this;
    if (!nextFnArgs) {
        nextFnArgs = [];
    }
    if (!nextFn) {
        nextFn = self.pseudoCallback;
    }
    console.log('unRegisterLongPressListener');
    if (self.configuration.settings.isBrowser) {
        (function() {
            nextFn.apply(self, nextFnArgs);
        })();
    } else {
        self.unregisterLongPressListener(function() {
            nextFn.apply(this, nextFnArgs);
        });
    }
}

myLaiSee.prototype.playSound = function(type) {
    var self = this;
    if (!self.configuration.settings.isBrowser) {
        self.playSoundByType(type);
    }
}

myLaiSee.prototype.pseudoCallback = function() {}

// ==============================================================
// Native hook call section [end]
// ==============================================================


// ==============================================================
// JSON proxy call section [start]
// ==============================================================
myLaiSee.prototype.joinMyLaiSeeGame = function() {
    var self = this;
    self.openInfoSection(iData.get('myLaiSeeNowStaff_topSection'), iData.get('myLaiSeeNowStaff_bottomSection'), iData.get('myLaiSeeNowStaff_info'));
    console.log(self.getParam4JoinMyLaiSeeGame());
    self.request({
        name: "joinMyLaiSeeGame",
        data: self.getParam4JoinMyLaiSeeGame,
        hideLoadingFlag: true,
        callback: self.callback4JoinMyLaiSeeGame,
        method: "post"
    });
}
myLaiSee.prototype.getParam4JoinMyLaiSeeGame = function() {
    var self = this;
    return {
        "requestName": "joinGame",
        "account": self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.account],
        "deviceId": self.deviceId,
        "sponsorCode": self.sponsorCode //Bill implement the changes for sponsor code
    };
}
myLaiSee.prototype.callback4JoinMyLaiSeeGame = function() {
    var self = this;
    return {
        "success": function(callback) {
            var data = callback.data;
            var gameResult = data.body.gameResult;
            iData.get('sponsorCode').val('');
            self.emptySponsorCodeVal(); //Bill implement the changes for sponsor code
            if (gameResult == 'Won' && data.body.prizeInfo) {
                self.isMyLaiSeeWon = true;
                self.newPrizeInfo.sponsor = data.body.prizeInfo.sponsor;
                self.newPrizeInfo.prizeId = data.body.prizeInfo.prizeId;
                self.newPrizeInfo.category = data.body.prizeInfo.category;
                self.newPrizeInfo.status = data.body.prizeInfo.status;
                self.displayLaisee();
            } else {
                self.isMyLaiSeeWon = false;
                self.showResult(iData.get('myLaiSeeNowStaff_info').find('div.ui-waiting'), iData.get('myLaiSeeNowStaff_info').find('div.ui-error'));
            }
        },
        "error": function(callback) {
            var data = callback.data;
            self.isMyLaiSeeWon = false;
            iData.get('sponsorCode').val('');
            self.emptySponsorCodeVal(); //Bill implement the changes for sponsor code
            try {
                if (callback.errorCode.match(/E001/) && data.header.errorMsg[0].code == '0009') {
                    iData.get('collectedSpan').text(data.header.errorMsg[0].desc);
					self.showResult(iData.get('myLaiSeeNowStaff_info').find('div.ui-waiting'), iData.get('myLaiSeeNowStaff_info').find('div.ui-error-collected'));
                    return;
                }
            } catch (e) {}
            self.showResult(iData.get('myLaiSeeNowStaff_info').find('div.ui-waiting'), iData.get('myLaiSeeNowStaff_info').find('div.ui-error'));
        }
    };
}

myLaiSee.prototype.unlockBonus = function() {
    var self = this;
    setTimeout(function() {
        self.request.call(self, {
            name: "unlockBonus",
            data: self.getParam4UnlockBonus,
            callback: self.callback4UnlockBonus,
            method: "post"
        });
    }, 1000);
}
myLaiSee.prototype.getParam4UnlockBonus = function() {
    var self = this;
    return {
        "account": self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.account],
        "deviceId": self.deviceId,
        "bonusId": self.laiseeListStaff[self._currentSlideIndex - 1].prizeId
    };
}
myLaiSee.prototype.callback4UnlockBonus = function() {
    var self = this;
    return {
        "success": function(callback) {
            var data = callback.data;

            if (data.body.status != 'Active') {
                self.unlockBonusTwice();
                return;
            }
            var days = Math.ceil((new Date(self.laiseeListStaff[self._currentSlideIndex - 1].expireDate) - new Date()) / (1000 * 60 * 60 * 24));
            self.laiseeListStaff[self._currentSlideIndex - 1].status = 'Active';
            $('#laiseeIcon' + (self._currentSlideIndex - 1)).removeClass('icon-laiseeLockedStaff');
            $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(1) label span').text(iData.get('i18n').tap2open)
            $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(2) label span').text(iData.get('i18n').expireDays.replace('~~1', days));
            // Nick added to hide expire days
            $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(2) label span').addClass("hidden");
        },
        "error": function(callback) {
            var data = callback.data;
        }
    };
}
myLaiSee.prototype.unlockBonusTwice = function() {
    var self = this;
    console.log('unlockBonusTwice');
    setTimeout(function() {
        self.request.call(self, {
            name: "unlockBonus",
            data: self.getParam4UnlockBonusTwice,
            callback: self.callback4UnlockBonusTwice,
            method: "post"
        });
    }, 1000);
}
myLaiSee.prototype.getParam4UnlockBonusTwice = function() {
    var self = this;
    return {
        "account": self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.account],
        "deviceId": self.deviceId,
        "bonusId": self.laiseeListStaff[self._currentSlideIndex - 1].prizeId
    };
}
myLaiSee.prototype.callback4UnlockBonusTwice = function() {
    var self = this;
    return {
        "success": function(callback) {
            var data = callback.data;
            if (data.body.status != 'Active') {
                // TODO wording
                $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(2) label span').text(iData.get('i18n').goToUnlock_err);
                self.prepareLongPress();
                return;
            }
            var days = Math.ceil((new Date(self.laiseeListStaff[self._currentSlideIndex - 1].expireDate) - new Date()) / (1000 * 60 * 60 * 24));
            self.laiseeListStaff[self._currentSlideIndex - 1].status = 'Active';
            $('#laiseeIcon' + (self._currentSlideIndex - 1)).removeClass('icon-laiseeLockedStaff');
            $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(1) label span').text(iData.get('i18n').tap2open)
            $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(2) label span').text(iData.get('i18n').expireDays.replace('~~1', days));
            // Nick added to hide expire days
            $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(2) label span').addClass("hidden");
        },
        "error": function(callback) {
            var data = callback.data;
        }
    };
}

myLaiSee.prototype.getMyPrizes = function() {
    var self = this;
    self.request({
        name: "getMyPrizes",
        data: self.getParam4GetMyPrizes,
        callback: self.callback4GetMyPrizes,
        method: "post"
    });
}
myLaiSee.prototype.getParam4GetMyPrizes = function() {
    var self = this;
    return {
        "account": self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.account],
        "deviceId": self.deviceId
    };
}
myLaiSee.prototype.callback4GetMyPrizes = function() {
    var self = this;
    return {
        "success": function(callback) {
            var data = callback.data;
            self.laiseeListStaff = data.body.prizeList;
            self.prepareLaiseeViewStaff();
        },
        "error": function(callback) {
            var data = callback.data;
        }
    };
}

myLaiSee.prototype.viewPrize = function() {
    var self = this;
    self.request({
        name: "viewPrize",
        data: self.getParam4ViewPrize,
        hideLoadingFlag: true,
        callback: self.callback4ViewPrize,
        method: "post"
    });
}
myLaiSee.prototype.getParam4ViewPrize = function() {
    var self = this;
    return {
        "account": self.userInfo[self.configuration.settings.GreenPacket.customerInfo.properties.account],
        "deviceId": self.deviceId,
        "prizeId": self.laiseeListStaff[self._currentSlideIndex - 1].prizeId
    };
}
myLaiSee.prototype.callback4ViewPrize = function() {
    var self = this;
    return {
        "success": function(callback) {
            var data = callback.data;
            console.log(self._currentSlideIndex);
            console.log(data.body);
            var prizeDetail = data.body.prizeDetail;
            self.currentMoneyStr = prizeDetail.currency + " " + prizeDetail.money;
            if (prizeDetail.status == 'Opened') {
                $("#laisee-open" + (self._currentSlideIndex - 1)).removeClass('hidden').find('div.cs-prize-money').text(prizeDetail.currency + " " + prizeDetail.money);
                $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(1) label span').text(iData.get('i18n').tap2redeem);
                $('#laiseeSlideWrapper div.ui-div-slide').eq(self._currentSlideIndex).find('div.slideContent div:nth-child(2) label span').text(iData.get('i18n').help4moreDetail);
                // Nick added to update the help button status end
                // expected to show the help button
                self.updateHelpButtonStatus();
                // Nick added to update the help button status end
            } else if (prizeDetail.status == 'Redeemed') {
                $("#laisee-open" + (self._currentSlideIndex - 1)).removeClass('hidden').find('div.cs-prize-money').text(prizeDetail.currency + " " + prizeDetail.money).find(" ~ div").removeClass('hidden').text(iData.get('i18n').redeemed);
                // Nick added to update the help button status end
                // expected to hide the help button
                self.updateHelpButtonStatus();
                // Nick added to update the help button status end
            } else {
                return;
            }
            // Nick added start
            $("#laiseeSlideWrapper div.ui-div-slide").eq(self._currentSlideIndex).find('div.slideContent div:nth-child(2) label span').removeClass("hidden");
            // Nick added end
            $("#laiseeVideo" + (self._currentSlideIndex - 1)).addClass('hidden');
            $("#laiseeIcon" + (self._currentSlideIndex - 1)).addClass('hidden');
        },
        "error": function(callback) {
            var data = callback.data;
        }
    };
}

// Nick added for help page start
myLaiSee.prototype.helpHasParsed = function() {
    var self = this;

    iData.get("btn-help-back").click(function() {
        self.goBack();
    });
};
// Nick added for help page end

// ==============================================================
// JSON proxy call section [end]
// ==============================================================

collectIscrollPluginInit = {
    self: null,
    myScroll: null,
    setTarget: function(obj) {
        self = obj;
    },
    begin: function() {
        collectIscrollPluginInit.myScroll = new iScroll('laiseeSlideWrapper', {
            snap: true,
            momentum: false,
            checkDOMChanges: true,
            hScrollbar: false,
            vScrollbar: false,
            vScroll: false,
            useTransition: true,
            onRefresh: function() {
                // reset the wrapper with to 60% of the client width
                this.wrapperW = self.constants.windowWidth;
                // reset the maxScrollX according to the number of LaiSees
                this.maxScrollX = -self.constants.windowWidth * (self.laiseeListStaff.length);
                // update the status of the indicators
                iData.get("indicator").children("div.active").removeClass("active");
                iData.get("indicator").children("div:eq(0)").addClass("active");
            },
            onScrollEnd: function() {
                //update indicator layout
                iData.get("indicator").children("div.active").removeClass("active");
                iData.get("indicator").children("div:nth-child(" + (this.currPageX + 1) + ")").addClass("active");
                console.log(this.currPageX);
                //trigger page slide event
                if (self._currentSlideIndex > this.currPageX) { // slide to previous
                    console.log('slide to prev');
                    if (self._currentSlideIndex == 0) {
                        return;
                    }

                    if (self._currentSlideIndex == 1) {
                        if (self.configuration.settings.isBrowser) {
                            self.showPrevSlide(this.currPageX);
                        } else {
                            self.prepareShakingStaff(self.showPrevSlide, [this.currPageX]);
                        }
                    } else {
                        self.showPrevSlide(this.currPageX);
                    }
                } else if (self._currentSlideIndex < this.currPageX) { // slide to next
                    console.log('slide to next');
                    if (self._currentSlideIndex == iData.get('indicator').find('div').length - 1) {
                        return;
                    }

                    if (self.configuration.settings.isBrowser) {
                        self.showNextSlide(this.currPageX);
                    } else {
                        self.cancelShaking(self.showNextSlide, [this.currPageX]);
                    }
                } else {
                    console.log('no slide');
                }
            }
        });
    }
};


//construct data model for the views
myLaiSee.prototype.buildModel = function() {
    iData.add({
        "myLaiSeeNowStaff_btn_menu": $('#myLaiSeeNowStaff_btn_menu'),

        "btnDelivered": $("#btnDelivered"),
        "btnReceived": $("#btnReceived"),

        // Nick added help button start
        "myLaiSeeNowStaff_btn_help": $("#myLaiSeeNowStaff_btn_help"),
        "btn-help-back": $("#btn-help-back"),
        // Nick added help button end
        "myLaiSeeNowStaff_topSection": $('#myLaiSeeNowStaff_topSection'),
        "myLaiSeeNowStaff_info": $('#myLaiSeeNowStaff_info'),
        "myLaiSeeNowStaff_bottomSection": $('#myLaiSeeNowStaff_bottomSection'),
        "congratsMsg": $('#congratsMsg'),
        "myLaiSeeLimit": $('#myLaiSeeLimit'),
        "myLaiSeeBonus": $('#myLaiSeeBonus'),
        "myLaiSeeCurrency": $('#myLaiSeeCurrency'),
        "myLaiSeeAmount": $('#myLaiSeeAmount'),
        "sentLaiseeAmount": $('#sentLaiseeAmount'),
        "greenAmount": $('#greenAmount'),
        "bonusAmount": $('#bonusAmount'),
        "indicator": $('#indicator'),
        "laiSeesScroller": $('#laiSeesScroller'),
        "laiSeesScroller": $('#laiSeesScroller'),
        "sponsorCode": $('#sponsorCode'),
        "myLaiSeeNow_btn_setting": $('#myLaiSeeNow_btn_setting'),
        "myLaiSeeNow_code1": $('#myLaiSeeNow_code1'),
        "myLaiSeeNow_code2": $('#myLaiSeeNow_code2'),
        "myLaiSeeNow_setting_save": $('#myLaiSeeNow_setting_save'),
        "myLaiSeeNow_setting_cancel": $('#myLaiSeeNow_setting_cancel'),
        "myLaiSeeNow_setting": $('#myLaiSeeNow_setting'),
        "myLaiSeeNow_code_setting": $('#myLaiSeeNow_code_setting'),
        "collectedSpan": $('#collectedSpan'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#'),
        "": $('#')
    });
}

myLaiSee.superclass = iFunction;
myLaiSee.start = function() {
    return new myLaiSee();
}
iClass(myLaiSee);